﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DoAnWebsite.Models;
using Ext.Net;
using Ext.Net.MVC;
using System.Linq.Dynamic;

namespace DoAnWebsite.Controllers
{
    public class VideoController : Controller
    {
        //Video
        private static DoAnWebsite_Entities db = new DoAnWebsite_Entities();
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult ListVideo()
        {
            Session["includeInActiveVideo"] = false;
            Session["CharFilterVideo"] = "";
            return View();
        }

        public ActionResult IncludeInActive()
        {
            var store = X.GetCmp<Store>("VideoStore");

            Session["includeInActiveVideo"] = !(bool)Session["includeInActiveVideo"];

            store.Reload();
            return this.Direct();
        }

        [DirectMethod]
        public ActionResult CharFilterVideo(string filterstring)
        {
            var store = X.GetCmp<Store>("VideoStore");
            Session["CharFilterVideo"] = filterstring;
            store.Reload();
            return this.Direct();
        }

        public ActionResult BindingVideoStore(StoreRequestParameters parameters)
        {
            var sampleData = (db.Videos.Join(db.GroupVideos, tab1 => tab1.GroupVideoID, tab2 => tab2.GroupVideoId,
                                           (tab1, tab2) => new
                                           {
                                               tab1.VideoId,
                                               tab1.Name,
                                               tab1.Date,
                                               tab1.Title,
                                               tab2.GVName,
                                               tab1.Views,
                                               tab1.Active
                                           })
                             );


            bool includeInActive = (bool)Session["includeInActiveVideo"];
            string charFilter = (string)Session["CharFilterVideo"];

            var result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active)));
            if ("0".Equals(charFilter))
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) &&
                    (ent.Name.StartsWith("0") || ent.Name.StartsWith("1") ||
                    ent.Name.StartsWith("2") || ent.Name.StartsWith("3") ||
                    ent.Name.StartsWith("4") || ent.Name.StartsWith("5") ||
                    ent.Name.StartsWith("6") || ent.Name.StartsWith("7") ||
                    ent.Name.StartsWith("8") || ent.Name.StartsWith("9")
                    )));
            }

            else
            {
                result = sampleData.Where(ent => ((includeInActive || (bool)ent.Active) && ent.Name.StartsWith(charFilter)));

            }

            // Sorting
            if (!string.IsNullOrEmpty(parameters.SimpleSort))
            {
                result = result.OrderBy(parameters.SimpleSort + (parameters.SimpleSortDirection == SortDirection.DESC ? " desc" : " asc"));
            }
            else
            {
                result = result.OrderBy(ent => ent.VideoId);
            }

            // Paging
            int limit = parameters.Limit;
            if ((parameters.Start + parameters.Limit) > result.Count())
            {
                limit = result.Count() - parameters.Start;
            }

            var rangeData = (parameters.Start < 0 || limit < 0) ? result : result.Skip(parameters.Start).Take(limit);
            return this.Store(rangeData.Select(ent => new { ent.VideoId, ent.Name, ent.Date, ent.Title, ent.GVName, ent.Views, ent.Active }), result.Count());
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult CreateVideo()
        {
            ViewBag.HideTextBox = false;
            ViewBag.GVideoId = new List<ListItem>();
            ViewBag.GVideoId = db.GroupVideos.ToList().Select(ent => new ListItem { Text = ent.GVName, Value = ent.GroupVideoId.ToString() });

            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateVideo(Video model)
        {
            if (ModelState.IsValid)
            {
                var upImage = X.GetCmp<FileUploadField>("UpImage");
                if (upImage.HasFile)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//UploadImage//" +
                                                  httpPostedFileBase.FileName);
                        model.Image = "/Content/UploadImage/" + httpPostedFileBase.FileName;
                    }
                }
                string[] temp = model.File.Split('=');
                model.File = "http://www.youtube.com/v/"+temp[1];
                model.Active = true;
                db.Videos.AddObject(model);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Create Video success!").Show();
                return this.FormPanel();
            }

            X.Msg.Notify("Non Sucess", "Create Video non success!").Show();

            return this.FormPanel();
        }

        [HttpGet]
        [AccessDeniedAuthorize(Roles = "administrators, users")]
        public ActionResult EditVideo(int id)
        {
            ViewBag.HideTextBox = false;
            ViewBag.GVideoId = new List<ListItem>();
            ViewBag.GVideoId = db.GroupVideos.ToList().Select(ent => new ListItem { Text = ent.GVName, Value = ent.GroupVideoId.ToString() });
            
            Video video = db.Videos.Single(m => m.VideoId == id);
            return View(video);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditVideo(Video model)
        {
            Video video1 = db.Videos.Single(c => c.VideoId == model.VideoId);
            if (ModelState.IsValid)
            {
                var upImage = X.GetCmp<FileUploadField>("UpImage");
                if (upImage.HasFile)
                {
                    var httpPostedFileBase = Request.Files[0];
                    if (httpPostedFileBase != null)
                    {
                        httpPostedFileBase.SaveAs(Server.MapPath("~/") + "//Content//UploadImage//" +
                                                  httpPostedFileBase.FileName);
                        model.Image = "/Content/UploadImage/" + httpPostedFileBase.FileName;
                    }
                }
                else
                {
                    model.Image = video1.Image;
                }
                db.Videos.Detach(video1);
                db.Videos.Attach(model);
                db.ObjectStateManager.ChangeObjectState(model, EntityState.Modified);
                db.SaveChanges();
                X.Msg.Notify("Sucess", "Edit GroupVideo success!").Show();
                return this.FormPanel();
            }
            X.Msg.Notify("Non Sucess", "Edit GroupVideo non success!").Show();
            return this.FormPanel();
        }
    }
}
